﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Comm
{
    /// <summary>
    /// 字符串截取类
    /// </summary>
    public class InterceptedString
    {
        /// <summary>
        /// 获取指定长度字符串
        /// </summary>
        /// <param name="content">字符串内容</param>
        /// <param name="Num">字节的长度</param>
        /// <returns></returns>
        public static string GetContent(object obj, int num)
        {
            if (obj == null)
            {
                return "";
            }
            string content = obj.ToString();
            if (System.Text.Encoding.Default.GetBytes(content).Length > num)
            {
                int i = 0;
                string str = "";
                while (true)
                {
                    string temp = str + content.Substring(i, 1);
                    if (System.Text.Encoding.Default.GetBytes(temp).Length <= num)
                    {
                        str = temp;
                    }
                    else
                    {
                        return str;
                    }
                    i++;
                }
            }
            return content;
        }

        /// <summary>
        /// 获取指定长度字符串
        /// </summary>
        /// <param name="content">字符串内容</param>
        /// <param name="num">字节的长度</param>
        /// <param name="endstring">是否加省略字符串</param>
        /// <returns>截取后的字符串</returns>
        public static string GetContent(object obj, int num, string endstring)
        {
            if (obj == null)
            {
                return "";
            }
            string content = obj.ToString().Trim();
            if (endstring != null && endstring.Length > 0)
            {
                if (System.Text.Encoding.Default.GetBytes(content).Length > num)
                {
                    return string.Format("{0}{1}", GetContent(content, num), endstring);
                }
            }
            return GetContent(content, num);
        }

        /// <summary>
        /// 判断字符串str的长度是否小于等于length(字节数)
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="length">长度(字节)</param>
        /// <returns>true：大于  false：满足条件(小于等于)</returns>
        public static bool CheckStringLength(string str, int length)
        {
            return System.Text.Encoding.Default.GetBytes(str).Length > length ? true : false;
        }

    }
}
